package com.shine.icis.ts;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Endpoint;


@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class TaskServerTool {
	
	private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static String service;
	private static String stopBat;
	private static String startBat;
	private static String url;
	private static String user;
	private static String password;
	
	static {
		Properties prop = new Properties();
		try {
			prop.load(TaskServerTool.class.getResourceAsStream("/run.properties"));
			service = prop.getProperty("service");
			//取到CMD的绝对路径
			File f = new File(prop.getProperty("stopBat"));
			stopBat = f.getAbsolutePath();
			f = new File(prop.getProperty("startBat"));
			startBat = f.getAbsolutePath();
			url = prop.getProperty("url");
			user = prop.getProperty("user");
			password = prop.getProperty("password");
			System.out.println(df.format(new Date()) + " 加载配置成功...");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 重启TASKSERVER工具
	 */
	@WebMethod
	public boolean restart() {
		try{
			System.out.println(df.format(new Date()) + " 开始重启TASKSERVER");
			Process ps = Runtime.getRuntime().exec(stopBat);
			//获取流等待此CMD命令执行结束
			BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
			String tem = br.readLine();
			while(tem != null) {
				System.out.println("CMD->" + tem);
				tem = br.readLine();
			}
			resetTaskStatus();
			Runtime.getRuntime().exec(startBat);
			System.out.println(df.format(new Date()) + " 结束重启TASKSERVER");
			return true;
		} catch(Exception e){
			e.printStackTrace();
			return false;
		}
		
	}
	
	/**
	 * 重置任务状态
	 */
	private void resetTaskStatus() throws Exception {
		Connection conn = null;
		Statement stmt = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver"); 
			conn = DriverManager.getConnection(url , user, password); 
			stmt = conn.createStatement();
			int i = stmt.executeUpdate("update e_task.tb_task t set t.status = null where t.status is not null");
			System.out.println(df.format(new Date()) + " 重置任务数：" + i);
		} finally {
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
	}
	
	public static void main(String[] arg) {
		TaskServerTool tsTool = new TaskServerTool();
		tsTool.restart();
		
		Endpoint.publish(service, tsTool);
		System.out.println(df.format(new Date()) + " 服务启动成功...");

	}
}
